home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / gdb-4.5 / dist / gdb / m68k-stub.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-02-22  |  32.9 KB  |  992 lines

  1. /****************************************************************************
  2.  
  3.         THIS SOFTWARE IS NOT COPYRIGHTED  
  4.    
  5.    HP offers the following for use in the public domain.  HP makes no
  6.    warranty with regard to the software or it's performance and the 
  7.    user accepts the software "AS IS" with all faults.
  8.  
  9.    HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD
  10.    TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  11.    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  12.  
  13. ****************************************************************************/
  14.  
  15. /****************************************************************************
  16.  *  Header: remcom.c,v 1.34 91/03/09 12:29:49 glenne Exp $                   
  17.  *
  18.  *  Module name: remcom.c $  
  19.  *  Revision: 1.34 $
  20.  *  Date: 91/03/09 12:29:49 $
  21.  *  Contributor:     Lake Stevens Instrument Division$
  22.  *  
  23.  *  Description:     low level support for gdb debugger. $
  24.  *
  25.  *  Considerations:  only works on target hardware $
  26.  *
  27.  *  Written by:      Glenn Engel $
  28.  *  ModuleState:     Experimental $ 
  29.  *
  30.  *  NOTES:           See Below $
  31.  * 
  32.  *  To enable debugger support, two things need to happen.  One, a
  33.  *  call to set_debug_traps() is necessary in order to allow any breakpoints
  34.  *  or error conditions to be properly intercepted and reported to gdb.
  35.  *  Two, a breakpoint needs to be generated to begin communication.  This
  36.  *  is most easily accomplished by a call to breakpoint().  Breakpoint()
  37.  *  simulates a breakpoint by executing a trap #1.
  38.  *  
  39.  *  Some explanation is probably necessary to explain how exceptions are
  40.  *  handled.  When an exception is encountered the 68000 pushes the current
  41.  *  program counter and status register onto the supervisor stack and then
  42.  *  transfers execution to a location specified in it's vector table.
  43.  *  The handlers for the exception vectors are hardwired to jmp to an address
  44.  *  given by the relation:  (exception - 256) * 6.  These are decending 
  45.  *  addresses starting from -6, -12, -18, ...  By allowing 6 bytes for
  46.  *  each entry, a jsr, jmp, bsr, ... can be used to enter the exception 
  47.  *  handler.  Using a jsr to handle an exception has an added benefit of
  48.  *  allowing a single handler to service several exceptions and use the
  49.  *  return address as the key differentiation.  The vector number can be
  50.  *  computed from the return address by [ exception = (addr + 1530) / 6 ].
  51.  *  The sole purpose of the routine _catchException is to compute the
  52.  *  exception number and push it on the stack in place of the return address.
  53.  *  The external function exceptionHandler() is
  54.  *  used to attach a specific handler to a specific 68k exception.
  55.  *  For 68020 machines, the ability to have a return address around just
  56.  *  so the vector can be determined is not necessary because the '020 pushes an
  57.  *  extra word onto the stack containing the vector offset
  58.  * 
  59.  *  Because gdb will sometimes write to the stack area to execute function
  60.  *  calls, this program cannot rely on using the supervisor stack so it
  61.  *  uses it's own stack area reserved in the int array remcomStack.  
  62.  * 
  63.  *************
  64.  *
  65.  *    The following gdb commands are supported:
  66.  * 
  67.  * command          function                               Return value
  68.  * 
  69.  *    g             return the value of the CPU registers  hex data or ENN
  70.  *    G             set the value of the CPU registers     OK or ENN
  71.  * 
  72.  *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
  73.  *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
  74.  * 
  75.  *    c             Resume at current address              SNN   ( signal NN)
  76.  *    cAA..AA       Continue at address AA..AA             SNN
  77.  * 
  78.  *    s             Step one instruction                   SNN
  79.  *    sAA..AA       Step one instruction from AA..AA       SNN
  80.  * 
  81.  *    k             kill
  82.  *
  83.  *    ?             What was the last sigval ?             SNN   (signal NN)
  84.  * 
  85.  * All commands and responses are sent with a packet which includes a 
  86.  * checksum.  A packet consists of 
  87.  * 
  88.  * $<packet info>#<checksum>.
  89.  * 
  90.  * where
  91.  * <packet info> :: <characters representing the command or response>
  92.  * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
  93.  * 
  94.  * When a packet is received, it is first acknowledged with either '+' or '-'.
  95.  * '+' indicates a successful transfer.  '-' indicates a failed transfer.
  96.  * 
  97.  * Example:
  98.  * 
  99.  * Host:                  Reply:
  100.  * $m0,10#2a               +$00010203040506070809101112131415#42
  101.  * 
  102.  ****************************************************************************/
  103.  
  104. #include <stdio.h>
  105. #include <string.h>
  106. #include <setjmp.h>
  107. #include "ansidecl.h"
  108.  
  109. /************************************************************************
  110.  *
  111.  * external low-level support routines 
  112.  */
  113. typedef void (*ExceptionHook)(int);   /* pointer to function with int parm */
  114. typedef void (*Function)();           /* pointer to a function */
  115.  
  116. extern putDebugChar();   /* write a single character      */
  117. extern getDebugChar();   /* read and return a single char */
  118.  
  119. extern Function exceptionHandler();  /* assign an exception handler */
  120. extern ExceptionHook exceptionHook;  /* hook variable for errors/exceptions */
  121.  
  122. /************************/
  123. /* FORWARD DECLARATIONS */
  124. /************************/
  125. static void
  126. initializeRemcomErrorFrame PARAMS ((void));
  127.  
  128. /************************************************************************/
  129. /* BUFMAX defines the maximum number of characters in inbound/outbound buffers*/
  130. /* at least NUMREGBYTES*2 are needed for register packets */
  131. #define BUFMAX 400
  132.  
  133. static char initialized;  /* boolean flag. != 0 means we've been initialized */
  134.  
  135. int     remote_debug;
  136. /*  debug >  0 prints ill-formed commands in valid packets & checksum errors */ 
  137.  
  138. static const char hexchars[]="0123456789abcdef";
  139.  
  140. /* there are 180 bytes of registers on a 68020 w/68881      */
  141. /* many of the fpa registers are 12 byte (96 bit) registers */
  142. #define NUMREGBYTES 180
  143. enum regnames {D0,D1,D2,D3,D4,D5,D6,D7, 
  144.                A0,A1,A2,A3,A4,A5,A6,A7, 
  145.                PS,PC,
  146.                FP0,FP1,FP2,FP3,FP4,FP5,FP6,FP7,
  147.                FPCONTROL,FPSTATUS,FPIADDR
  148.               };
  149.  
  150. typedef struct FrameStruct
  151. {
  152.     struct FrameStruct  *previous;
  153.     int       exceptionPC;      /* pc value when this frame created */
  154.     int       exceptionVector;  /* cpu vector causing exception     */
  155.     short     frameSize;        /* size of cpu frame in words       */
  156.     short     sr;               /* for 68000, this not always sr    */
  157.     int       pc;
  158.     short     format;
  159.     int       fsaveHeader;
  160.     int       morejunk[0];        /* exception frame, fp save... */
  161. } Frame;
  162.  
  163. #define FRAMESIZE 500
  164. int   gdbFrameStack[FRAMESIZE];
  165. static Frame *lastFrame;
  166.  
  167. /*
  168.  * these should not be static cuz they can be used outside this module
  169.  */
  170. int registers[NUMREGBYTES/4];
  171. int superStack;
  172.  
  173. #define STACKSIZE 10000
  174. int remcomStack[STACKSIZE/sizeof(int)];
  175. static int* stackPtr = &remcomStack[STACKSIZE/sizeof(int) - 1];
  176.  
  177. /*
  178.  * In many cases, the system will want to continue exception processing
  179.  * when a continue command is given.  
  180.  * oldExceptionHook is a function to invoke in this case.
  181.  */
  182.  
  183. static ExceptionHook oldExceptionHook;
  184.  
  185. /* the size of the exception stack on the 68020 varies with the type of
  186.  * exception.  The following table is the number of WORDS used
  187.  * for each exception format.
  188.  */
  189. const short exceptionSize[] = { 4,4,6,4,4,4,4,4,29,10,16,46,12,4,4,4 };
  190.  
  191. /************* jump buffer used for setjmp/longjmp **************************/
  192. jmp_buf remcomEnv;
  193.  
  194. /***************************  ASSEMBLY CODE MACROS *************************/
  195. /*                                        */
  196.  
  197. #ifdef __HAVE_68881__
  198. /* do an fsave, then remember the address to begin a restore from */
  199. #define SAVE_FP_REGS()    asm(" fsave   a0@-");        \
  200.               asm(" fmovemx fp0-fp7,_registers+72");        \
  201.               asm(" fmoveml fpcr/fpsr/fpi,_registers+168"); 
  202. #define RESTORE_FP_REGS()                              \
  203. asm("                                                \n\
  204.     fmoveml  _registers+168,fpcr/fpsr/fpi            \n\
  205.     fmovemx  _registers+72,fp0-fp7                   \n\
  206.     cmpl     #-1,a0@     |  skip frestore flag set ? \n\
  207.     beq      skip_frestore                           \n\
  208.     frestore a0@+                                    \n\
  209. skip_frestore:                                       \n\
  210. ");
  211.  
  212. #else
  213. #define SAVE_FP_REGS()
  214. #define RESTORE_FP_REGS()
  215. #endif /* __HAVE_68881__ */
  216.  
  217. #ifdef __STDC__
  218. void return_to_super(void);
  219. void return_to_user(void);
  220. #else
  221. void return_to_super();
  222. void return_to_user();
  223. #endif
  224.  
  225. asm("
  226. .text
  227. .globl _return_to_super
  228. _return_to_super:
  229.         movel   _registers+60,sp /* get new stack pointer */        
  230.         movel   _lastFrame,a0   /* get last frame info  */              
  231.         bra     return_to_any
  232.  
  233. .globl _return_to_user
  234. _return_to_user:
  235.         movel   _registers+60,a0 /* get usp */                          
  236.         movel   a0,usp           /* set usp */                
  237.         movel   _superStack,sp  /* get original stack pointer */        
  238.  
  239. return_to_any:
  240.         movel   _lastFrame,a0   /* get last frame info  */              
  241.         movel   a0@+,_lastFrame /* link in previous frame     */        
  242.         addql   #8,a0           /* skip over pc, vector#*/              
  243.         movew   a0@+,d0         /* get # of words in cpu frame */       
  244.         addw    d0,a0           /* point to end of data        */       
  245.         addw    d0,a0           /* point to end of data        */       
  246.         movel   a0,a1                                                   
  247. #                                                                       
  248. # copy the stack frame                                                  
  249.         subql   #1,d0                                                   
  250. copyUserLoop:                                                               
  251.         movew   a1@-,sp@-                                               
  252.         dbf     d0,copyUserLoop                                             
  253. ");                                                                     
  254.         RESTORE_FP_REGS()                                              
  255.    asm("   moveml  _registers,d0-d7/a0-a6");                    
  256.    asm("   rte");  /* pop and go! */                                    
  257.  
  258. #define DISABLE_INTERRUPTS()   asm("         oriw   #0x0700,sr");
  259. #define BREAKPOINT() asm("   trap #1");
  260.  
  261. /* this function is called immediately when a level 7 interrupt occurs */
  262. /* if the previous interrupt level was 7 then we're already servicing  */
  263. /* this interrupt and an rte is in order to return to the debugger.    */
  264. /* For the 68000, the offset for sr is 6 due to the jsr return address */
  265. asm("
  266. .text
  267. .globl __debug_level7
  268. __debug_level7:
  269.     movew   d0,sp@-");
  270. #ifdef mc68020
  271. asm("    movew   sp@(2),d0");
  272. #else
  273. asm("    movew   sp@(6),d0");
  274. #endif
  275. asm("    andiw   #0x700,d0
  276.     cmpiw   #0x700,d0
  277.     beq     _already7
  278.         movew   sp@+,d0    
  279.         bra     __catchException
  280. _already7:
  281.     movew   sp@+,d0");
  282. #ifndef mc68020
  283. asm("    lea     sp@(4),sp");     /* pull off 68000 return address */
  284. #endif
  285. asm("    rte");
  286.  
  287. extern void _catchException PARAMS ((void));
  288.  
  289. #ifdef mc68020
  290. /* This function is called when a 68020 exception occurs.  It saves
  291.  * all the cpu and fpcp regs in the _registers array, creates a frame on a
  292.  * linked list of frames which has the cpu and fpcp stack frames needed
  293.  * to properly restore the context of these processors, and invokes
  294.  * an exception handler (remcom_handler).
  295.  *
  296.  * stack on entry:                       stack on exit:
  297.  *   N bytes of junk                     exception # MSWord
  298.  *   Exception Format Word               exception # MSWord
  299.  *   Program counter LSWord              
  300.  *   Program counter MSWord             
  301.  *   Status Register                    
  302.  *                                       
  303.  *                                       
  304.  */
  305. asm(" 
  306. .text
  307. .globl __catchException
  308. __catchException:");
  309. DISABLE_INTERRUPTS();
  310. asm("
  311.         moveml  d0-d7/a0-a6,_registers /* save registers        */
  312.     movel    _lastFrame,a0    /* last frame pointer */
  313. ");
  314. SAVE_FP_REGS();        
  315. asm("
  316.     lea     _registers,a5   /* get address of registers     */
  317.         movew   sp@,d1          /* get status register          */
  318.         movew   d1,a5@(66)      /* save sr             */    
  319.     movel   sp@(2),a4       /* save pc in a4 for later use  */
  320.         movel   a4,a5@(68)      /* save pc in _regisers[]          */
  321.  
  322. #
  323. # figure out how many bytes in the stack frame
  324.     movew   sp@(6),d0    /* get '020 exception format    */
  325.         movew   d0,d2           /* make a copy of format word   */
  326.         andiw   #0xf000,d0      /* mask off format type         */
  327.         rolw    #5,d0           /* rotate into the low byte *2  */
  328.         lea     _exceptionSize,a1   
  329.         addw    d0,a1           /* index into the table         */
  330.     movew   a1@,d0          /* get number of words in frame */
  331.         movew   d0,d3           /* save it                      */
  332.         subw    d0,a0        /* adjust save pointer          */
  333.         subw    d0,a0        /* adjust save pointer(bytes)   */
  334.     movel   a0,a1           /* copy save pointer            */
  335.     subql   #1,d0           /* predecrement loop counter    */
  336. #
  337. # copy the frame
  338. saveFrameLoop:
  339.     movew      sp@+,a1@+
  340.     dbf     d0,saveFrameLoop
  341. #
  342. # now that the stack has been clenaed,
  343. # save the a7 in use at time of exception
  344.         movel   sp,_superStack  /* save supervisor sp           */
  345.         andiw   #0x2000,d1      /* were we in supervisor mode ? */
  346.         beq     userMode       
  347.         movel   a7,a5@(60)      /* save a7                  */
  348.         bra     a7saveDone
  349. userMode:  
  350.     movel   usp,a1        
  351.         movel   a1,a5@(60)      /* save user stack pointer    */
  352. a7saveDone:
  353.  
  354. #
  355. # save size of frame
  356.         movew   d3,a0@-
  357.  
  358. #
  359. # compute exception number
  360.     andl    #0xfff,d2       /* mask off vector offset    */
  361.     lsrw    #2,d2       /* divide by 4 to get vect num    */
  362.         movel   d2,a0@-         /* save it                      */
  363. #
  364. # save pc causing exception
  365.         movel   a4,a0@-
  366. #
  367. # save old frame link and set the new value
  368.     movel    _lastFrame,a1    /* last frame pointer */
  369.     movel   a1,a0@-        /* save pointer to prev frame    */
  370.         movel   a0,_lastFrame
  371.  
  372.         movel   d2,sp@-        /* push exception num           */
  373.     movel   _exceptionHook,a0  /* get address of handler */
  374.         jbsr    a0@             /* and call it */
  375.         clrl    sp@             /* replace exception num parm with frame ptr */
  376.         jbsr     __returnFromException   /* jbsr, but never returns */
  377. ");
  378. #else /* mc68000 */
  379. /* This function is called when an exception occurs.  It translates the
  380.  * return address found on the stack into an exception vector # which
  381.  * is then handled by either handle_exception or a system handler.
  382.  * _catchException provides a front end for both.  
  383.  *
  384.  * stack on entry:                       stack on exit:
  385.  *   Program counter MSWord              exception # MSWord 
  386.  *   Program counter LSWord              exception # MSWord
  387.  *   Status Register                     
  388.  *   Return Address  MSWord              
  389.  *   Return Address  LSWord             
  390.  */
  391. asm("
  392. .text
  393. .globl __catchException
  394. __catchException:");
  395. DISABLE_INTERRUPTS();
  396. asm("
  397.         moveml d0-d7/a0-a6,_registers  /* save registers               */
  398.     movel    _lastFrame,a0    /* last frame pointer */
  399. ");
  400. SAVE_FP_REGS();        
  401. asm("
  402.         lea     _registers,a5   /* get address of registers     */
  403.         movel   sp@+,d2         /* pop return address           */
  404.     addl     #1530,d2        /* convert return addr to     */
  405.     divs     #6,d2       /*  exception number        */
  406.     extl    d2   
  407.  
  408.         moveql  #3,d3           /* assume a three word frame     */
  409.  
  410.         cmpiw   #3,d2           /* bus error or address error ? */
  411.         bgt     normal          /* if >3 then normal error      */
  412.         movel   sp@+,a0@-       /* copy error info to frame buff*/
  413.         movel   sp@+,a0@-       /* these are never used         */
  414.         moveql  #7,d3           /* this is a 7 word frame       */
  415.      
  416. normal:   
  417.     movew   sp@+,d1         /* pop status register          */
  418.         movel   sp@+,a4         /* pop program counter          */
  419.         movew   d1,a5@(66)      /* save sr             */    
  420.         movel   a4,a5@(68)      /* save pc in _regisers[]          */
  421.         movel   a4,a0@-         /* copy pc to frame buffer      */
  422.     movew   d1,a0@-         /* copy sr to frame buffer      */
  423.  
  424.         movel   sp,_superStack  /* save supervisor sp          */
  425.  
  426.         andiw   #0x2000,d1      /* were we in supervisor mode ? */
  427.         beq     userMode       
  428.         movel   a7,a5@(60)      /* save a7                  */
  429.         bra     saveDone             
  430. userMode:
  431.         movel   usp,a1        /* save user stack pointer     */
  432.         movel   a1,a5@(60)      /* save user stack pointer    */
  433. saveDone:
  434.  
  435.         movew   d3,a0@-         /* push frame size in words     */
  436.         movel   d2,a0@-         /* push vector number           */
  437.         movel   a4,a0@-         /* push exception pc            */
  438.  
  439. #
  440. # save old frame link and set the new value
  441.     movel    _lastFrame,a1    /* last frame pointer */
  442.     movel   a1,a0@-        /* save pointer to prev frame    */
  443.         movel   a0,_lastFrame
  444.  
  445.         movel   d2,sp@-        /* push exception num           */
  446.     movel   _exceptionHook,a0  /* get address of handler */
  447.         jbsr    a0@             /* and call it */
  448.         clrl    sp@             /* replace exception num parm with frame ptr */
  449.         jbsr     __returnFromException   /* jbsr, but never returns */
  450. ");
  451. #endif
  452.  
  453.  
  454. /*
  455.  * remcomHandler is a front end for handle_exception.  It moves the
  456.  * stack pointer into an area reserved for debugger use in case the
  457.  * breakpoint happened in supervisor mode.
  458.  */
  459. asm("_remcomHandler:");
  460. asm("           addl    #4,sp");        /* pop off return address     */
  461. asm("           movel   sp@+,d0");      /* get the exception number   */
  462. asm("        movel   _stackPtr,sp"); /* move to remcom stack area  */
  463. asm("        movel   d0,sp@-");    /* push exception onto stack  */
  464. asm("        jbsr    _handle_exception");    /* this never returns */
  465. asm("           rts");                  /* return */
  466.  
  467. void _returnFromException( Frame *frame )
  468. {
  469.     /* if no passed in frame, use the last one */
  470.     if (! frame)
  471.     {
  472.         frame = lastFrame;
  473.     frame->frameSize = 4;
  474.         frame->format = 0;
  475.         frame->fsaveHeader = -1; /* restore regs, but we dont have fsave info*/
  476.     }
  477.  
  478. #ifndef mc68020
  479.     /* a 68000 cannot use the internal info pushed onto a bus error
  480.      * or address error frame when doing an RTE so don't put this info
  481.      * onto the stack or the stack will creep every time this happens.
  482.      */
  483.     frame->frameSize=3;
  484. #endif
  485.  
  486.     /* throw away any frames in the list after this frame */
  487.     lastFrame = frame;
  488.  
  489.     frame->sr = registers[(int) PS];
  490.     frame->pc = registers[(int) PC];
  491.  
  492.     if (registers[(int) PS] & 0x2000)
  493.     { 
  494.         /* return to supervisor mode... */
  495.         return_to_super();
  496.     }
  497.     else
  498.     { /* return to user mode */
  499.         return_to_user();
  500.     }
  501. }
  502.  
  503. int hex(ch)
  504. char ch;
  505. {
  506.   if ((ch >= 'a') && (ch <= 'f')) return (ch-'a'+10);
  507.   if ((ch >= '0') && (ch <= '9')) return (ch-'0');
  508.   if ((ch >= 'A') && (ch <= 'F')) return (ch-'A'+10);
  509.   return (-1);
  510. }
  511.  
  512.  
  513. /* scan for the sequence $<data>#<checksum>     */
  514. void getpacket(buffer)
  515. char * buffer;
  516. {
  517.   unsigned char checksum;
  518.   unsigned char xmitcsum;
  519.   int  i;
  520.   int  count;
  521.   char ch;
  522.   
  523.   do {
  524.     /* wait around for the start character, ignore all other characters */
  525.     while ((ch = getDebugChar()) != '$'); 
  526.     checksum = 0;
  527.     xmitcsum = -1;
  528.     
  529.     count = 0;
  530.     
  531.     /* now, read until a # or end of buffer is found */
  532.     while (count < BUFMAX) {
  533.       ch = getDebugChar();
  534.       if (ch == '#') break;
  535.       checksum = checksum + ch;
  536.       buffer[count] = ch;
  537.       count = count + 1;
  538.       }
  539.     buffer[count] = 0;
  540.  
  541.     if (ch == '#') {
  542.       xmitcsum = hex(getDebugChar()) << 4;
  543.       xmitcsum += hex(getDebugChar());
  544.       if ((remote_debug ) && (checksum != xmitcsum)) {
  545.         fprintf(stderr,"bad checksum.  My count = 0x%x, sent=0x%x. buf=%s\n",
  546.                              checksum,xmitcsum,buffer);
  547.       }
  548.       
  549.       if (checksum != xmitcsum) putDebugChar('-');  /* failed checksum */ 
  550.       else {
  551.      putDebugChar('+');  /* successful transfer */
  552.      /* if a sequence char is present, reply the sequence ID */
  553.      if (buffer[2] == ':') {
  554.         putDebugChar( buffer[0] );
  555.         putDebugChar( buffer[1] );
  556.         /* remove sequence chars from buffer */
  557.         count = strlen(buffer);
  558.         for (i=3; i <= count; i++) buffer[i-3] = buffer[i];
  559.      } 
  560.       } 
  561.     } 
  562.   } while (checksum != xmitcsum);
  563.   
  564. }
  565.  
  566. /* send the packet in buffer.  The host get's one chance to read it.  
  567.    This routine does not wait for a positive acknowledge.  */
  568.  
  569.  
  570. void putpacket(buffer)
  571. char * buffer;
  572. {
  573.   unsigned char checksum;
  574.   int  count;
  575.   char ch;
  576.   
  577.   /*  $<packet info>#<checksum>. */
  578.   do {
  579.   putDebugChar('$');
  580.   checksum = 0;
  581.   count    = 0;
  582.   
  583.   while (ch=buffer[count]) {
  584.     if (! putDebugChar(ch)) return;
  585.     checksum += ch;
  586.     count += 1;
  587.   }
  588.   
  589.   putDebugChar('#');
  590.   putDebugChar(hexchars[checksum >> 4]);
  591.   putDebugChar(hexchars[checksum % 16]);
  592.  
  593.   } while (1 == 0);  /* (getDebugChar() != '+'); */
  594.   
  595. }
  596.  
  597. char  remcomInBuffer[BUFMAX];
  598. char  remcomOutBuffer[BUFMAX];
  599. static short error;
  600.  
  601.  
  602. void debug_error(format, parm)
  603. char * format;
  604. char * parm;
  605. {
  606.   if (remote_debug) fprintf(stderr,format,parm);
  607. }
  608.  
  609. /* convert the memory pointed to by mem into hex, placing result in buf */
  610. /* return a pointer to the last char put in buf (null) */
  611. char* mem2hex(mem, buf, count)
  612. char* mem;
  613. char* buf;
  614. int   count;
  615. {
  616.       int i;
  617.       unsigned char ch;
  618.       for (i=0;i<count;i++) {
  619.           ch = *mem++;
  620.           *buf++ = hexchars[ch >> 4];
  621.           *buf++ = hexchars[ch % 16];
  622.       }
  623.       *buf = 0; 
  624.       return(buf);
  625. }
  626.  
  627. /* convert the hex array pointed to by buf into binary to be placed in mem */
  628. /* return a pointer to the character AFTER the last byte written */
  629. char* hex2mem(buf, mem, count)
  630. char* buf;
  631. char* mem;
  632. int   count;
  633. {
  634.       int i;
  635.       unsigned char ch;
  636.       for (i=0;i<count;i++) {
  637.           ch = hex(*buf++) << 4;
  638.           ch = ch + hex(*buf++);
  639.           *mem++ = ch;
  640.       }
  641.       return(mem);
  642. }
  643.  
  644. /* a bus error has occurred, perform a longjmp
  645.    to return execution and allow handling of the error */
  646.  
  647. void handle_buserror()
  648. {
  649.   longjmp(remcomEnv,1);
  650. }
  651.  
  652. /* this function takes the 68000 exception number and attempts to 
  653.    translate this number into a unix compatible signal value */
  654. int computeSignal( exceptionVector )
  655. int exceptionVector;
  656. {
  657.   int sigval;
  658.   switch (exceptionVector) {
  659.     case 2 : sigval = 10; break; /* bus error           */
  660.     case 3 : sigval = 10; break; /* address error       */
  661.     case 4 : sigval = 4;  break; /* illegal instruction */
  662.     case 5 : sigval = 8;  break; /* zero divide         */
  663.     case 6 : sigval = 16; break; /* chk instruction     */
  664.     case 7 : sigval = 16; break; /* trapv instruction   */
  665.     case 8 : sigval = 11; break; /* privilege violation */
  666.     case 9 : sigval = 5;  break; /* trace trap          */
  667.     case 10: sigval = 4;  break; /* line 1010 emulator  */
  668.     case 11: sigval = 4;  break; /* line 1111 emulator  */
  669.     case 13: sigval = 8;  break; /* floating point err  */
  670.     case 31: sigval = 2;  break; /* interrupt           */
  671.     case 33: sigval = 5;  break; /* breakpoint          */
  672.     case 40: sigval = 8;  break; /* floating point err  */
  673.     case 48: sigval = 8;  break; /* floating point err  */
  674.     case 49: sigval = 8;  break; /* floating point err  */
  675.     case 50: sigval = 8;  break; /* zero divide         */
  676.     case 51: sigval = 8;  break; /* underflow           */
  677.     case 52: sigval = 8;  break; /* operand error       */
  678.     case 53: sigval = 8;  break; /* overflow            */
  679.     case 54: sigval = 8;  break; /* NAN                 */
  680.     default: 
  681.       sigval = 7;         /* "software generated"*/
  682.   }
  683.   return (sigval);
  684. }
  685.  
  686. /**********************************************/
  687. /* WHILE WE FIND NICE HEX CHARS, BUILD AN INT */
  688. /* RETURN NUMBER OF CHARS PROCESSED           */
  689. /**********************************************/
  690. int hexToInt(char **ptr, int *intValue)
  691. {
  692.     int numChars = 0;
  693.     int hexValue;
  694.     
  695.     *intValue = 0;
  696.  
  697.     while (**ptr)
  698.     {
  699.         hexValue = hex(**ptr);
  700.         if (hexValue >=0)
  701.         {
  702.             *intValue = (*intValue <<4) | hexValue;
  703.             numChars ++;
  704.         }
  705.         else
  706.             break;
  707.         
  708.         (*ptr)++;
  709.     }
  710.  
  711.     return (numChars);
  712. }
  713.  
  714. /*
  715.  * This function does all command procesing for interfacing to gdb.
  716.  */
  717. void handle_exception(int exceptionVector)
  718. {
  719.   int    sigval;
  720.   int    addr, length;
  721.   char * ptr;
  722.   int    newPC;
  723.   Frame  *frame;
  724.   
  725.   if (remote_debug) printf("vector=%d, sr=0x%x, pc=0x%x\n", 
  726.                 exceptionVector,
  727.                 registers[ PS ], 
  728.                 registers[ PC ]);
  729.  
  730.   /* reply to host that an exception has occurred */
  731.   sigval = computeSignal( exceptionVector );
  732.   remcomOutBuffer[0] = 'S';
  733.   remcomOutBuffer[1] =  hexchars[sigval >> 4];
  734.   remcomOutBuffer[2] =  hexchars[sigval % 16];
  735.   remcomOutBuffer[3] = 0;
  736.  
  737.   putpacket(remcomOutBuffer); 
  738.  
  739.   while (1==1) { 
  740.     error = 0;
  741.     remcomOutBuffer[0] = 0;
  742.     getpacket(remcomInBuffer);
  743.     switch (remcomInBuffer[0]) {
  744.       case '?' :   remcomOutBuffer[0] = 'S';
  745.                    remcomOutBuffer[1] =  hexchars[sigval >> 4];
  746.                    remcomOutBuffer[2] =  hexchars[sigval % 16];
  747.                    remcomOutBuffer[3] = 0;
  748.                  break; 
  749.       case 'd' : remote_debug = !(remote_debug);  /* toggle debug flag */
  750.                  break; 
  751.       case 'g' : /* return the value of the CPU registers */
  752.                 mem2hex((char*) registers, remcomOutBuffer, NUMREGBYTES);
  753.                 break;
  754.       case 'G' : /* set the value of the CPU registers - return OK */
  755.                 hex2mem(&remcomInBuffer[1], (char*) registers, NUMREGBYTES);
  756.                 strcpy(remcomOutBuffer,"OK");
  757.                 break;
  758.       
  759.       /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
  760.       case 'm' : 
  761.             if (setjmp(remcomEnv) == 0)
  762.                 {
  763.                     exceptionHandler(2,handle_buserror); 
  764.  
  765.             /* TRY TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
  766.                     ptr = &remcomInBuffer[1];
  767.                     if (hexToInt(&ptr,&addr))
  768.                         if (*(ptr++) == ',')
  769.                             if (hexToInt(&ptr,&length)) 
  770.                             {
  771.                                 ptr = 0;
  772.                                 mem2hex((char*) addr, remcomOutBuffer, length);
  773.                             }
  774.  
  775.                     if (ptr)
  776.                     {
  777.               strcpy(remcomOutBuffer,"E01");
  778.               debug_error("malformed read memory command: %s",remcomInBuffer);
  779.                   }     
  780.                 } 
  781.         else {
  782.           exceptionHandler(2,_catchException);   
  783.           strcpy(remcomOutBuffer,"E03");
  784.           debug_error("bus error");
  785.           }     
  786.                 
  787.         /* restore handler for bus error */
  788.         exceptionHandler(2,_catchException);   
  789.         break;
  790.       
  791.       /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
  792.       case 'M' : 
  793.             if (setjmp(remcomEnv) == 0) {
  794.             exceptionHandler(2,handle_buserror); 
  795.                     
  796.             /* TRY TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
  797.                     ptr = &remcomInBuffer[1];
  798.                     if (hexToInt(&ptr,&addr))
  799.                         if (*(ptr++) == ',')
  800.                             if (hexToInt(&ptr,&length))
  801.                                 if (*(ptr++) == ':')
  802.                                 {
  803.                                     hex2mem(ptr, (char*) addr, length);
  804.                                     ptr = 0;
  805.                                     strcpy(remcomOutBuffer,"OK");
  806.                                 }
  807.                     if (ptr)
  808.                     {
  809.               strcpy(remcomOutBuffer,"E02");
  810.               debug_error("malformed write memory command: %s",remcomInBuffer);
  811.               }     
  812.                 } 
  813.         else {
  814.           exceptionHandler(2,_catchException);   
  815.           strcpy(remcomOutBuffer,"E03");
  816.           debug_error("bus error");
  817.           }     
  818.  
  819.                 /* restore handler for bus error */
  820.                 exceptionHandler(2,_catchException);   
  821.                 break;
  822.      
  823.      /* cAA..AA    Continue at address AA..AA(optional) */
  824.      /* sAA..AA   Step one instruction from AA..AA(optional) */
  825.      case 'c' : 
  826.      case 's' : 
  827.           /* try to read optional parameter, pc unchanged if no parm */
  828.          ptr = &remcomInBuffer[1];
  829.          if (hexToInt(&ptr,&addr))
  830.              registers[ PC ] = addr;
  831.              
  832.           newPC = registers[ PC];
  833.           
  834.           /* clear the trace bit */
  835.           registers[ PS ] &= 0x7fff;
  836.           
  837.           /* set the trace bit if we're stepping */
  838.           if (remcomInBuffer[0] == 's') registers[ PS ] |= 0x8000;
  839.           
  840.           /*
  841.            * look for newPC in the linked list of exception frames.
  842.            * if it is found, use the old frame it.  otherwise,
  843.            * fake up a dummy frame in returnFromException().
  844.            */
  845.           if (remote_debug) printf("new pc = 0x%x\n",newPC);
  846.           frame = lastFrame;
  847.           while (frame)
  848.           {
  849.               if (remote_debug)
  850.                   printf("frame at 0x%x has pc=0x%x, except#=%d\n",
  851.                          frame,frame->exceptionPC,
  852.                          frame->exceptionVector);
  853.               if (frame->exceptionPC == newPC) break;  /* bingo! a match */
  854.               /*
  855.                * for a breakpoint instruction, the saved pc may
  856.                * be off by two due to re-executing the instruction
  857.                * replaced by the trap instruction.  Check for this.
  858.                */
  859.               if ((frame->exceptionVector == 33) &&
  860.                   (frame->exceptionPC == (newPC+2))) break;
  861.               if (frame == frame->previous)
  862.           {
  863.               frame = 0; /* no match found */ 
  864.               break; 
  865.           }
  866.           frame = frame->previous;
  867.           }
  868.           
  869.           /*
  870.            * If we found a match for the PC AND we are not returning
  871.            * as a result of a breakpoint (33),
  872.            * trace exception (9), nmi (31), jmp to
  873.            * the old exception handler as if this code never ran.
  874.            */
  875.           if (frame) 
  876.           {
  877.               if ((frame->exceptionVector != 9)  && 
  878.                   (frame->exceptionVector != 31) && 
  879.                   (frame->exceptionVector != 33))
  880.               { 
  881.                   /*
  882.                    * invoke the previous handler.
  883.                    */
  884.                   if (oldExceptionHook)
  885.                       (*oldExceptionHook) (frame->exceptionVector);
  886.                   newPC = registers[ PC ];    /* pc may have changed  */
  887.                   if (newPC != frame->exceptionPC)
  888.                   {
  889.                       if (remote_debug)
  890.                           printf("frame at 0x%x has pc=0x%x, except#=%d\n",
  891.                                  frame,frame->exceptionPC,
  892.                                  frame->exceptionVector);
  893.                       /* re-use the last frame, we're skipping it (longjump?)*/
  894.               frame = (Frame *) 0;
  895.                   _returnFromException( frame );  /* this is a jump */
  896.                   }
  897.               }
  898.           }         
  899.  
  900.           /* if we couldn't find a frame, create one */
  901.           if (frame == 0)
  902.       {
  903.               frame = lastFrame -1 ;
  904.           
  905.           /* by using a bunch of print commands with breakpoints,
  906.                  it's possible for the frame stack to creep down.  If it creeps
  907.          too far, give up and reset it to the top.  Normal use should
  908.                  not see this happen.
  909.               */
  910.           if ((unsigned int) (frame-2) < (unsigned int) &gdbFrameStack)
  911.               {
  912.                  initializeRemcomErrorFrame();
  913.                  frame = lastFrame; 
  914.           }
  915.               frame->previous = lastFrame;
  916.               lastFrame = frame;
  917.               frame = 0;  /* null so _return... will properly initialize it */ 
  918.       }    
  919.       
  920.       _returnFromException( frame ); /* this is a jump */
  921.  
  922.           break;
  923.           
  924.       /* kill the program */
  925.       case 'k' :  /* do nothing */
  926.                 break;
  927.       } /* switch */ 
  928.     
  929.     /* reply to the request */
  930.     putpacket(remcomOutBuffer); 
  931.     }
  932. }
  933.  
  934.  
  935. #ifdef __STDC__
  936. void initializeRemcomErrorFrame(void)
  937. #else
  938. void initializeRemcomErrorFrame()
  939. #endif
  940. {
  941.     lastFrame = ((Frame *) &gdbFrameStack[FRAMESIZE-1]) - 1;
  942.     lastFrame->previous = lastFrame;
  943. }
  944.  
  945. /* this function is used to set up exception handlers for tracing and 
  946.    breakpoints */
  947. void set_debug_traps()
  948. {
  949. extern void _debug_level7();
  950. extern void remcomHandler();
  951. int exception;
  952.  
  953.   initializeRemcomErrorFrame();
  954.   stackPtr  = &remcomStack[STACKSIZE/sizeof(int) - 1];
  955.  
  956.   for (exception = 2; exception <= 23; exception++)
  957.       exceptionHandler(exception,_catchException);   
  958.  
  959.   /* level 7 interrupt              */
  960.   exceptionHandler(31,_debug_level7);    
  961.   
  962.   /* breakpoint exception (trap #1) */
  963.   exceptionHandler(33,_catchException);
  964.   
  965.   /* floating point error (trap #8) */
  966.   exceptionHandler(40,_catchException);
  967.   
  968.   /* 48 to 54 are floating point coprocessor errors */
  969.   for (exception = 48; exception <= 54; exception++)
  970.       exceptionHandler(exception,_catchException);   
  971.  
  972.   if (oldExceptionHook != remcomHandler)
  973.   {
  974.       oldExceptionHook = exceptionHook;
  975.       exceptionHook    = remcomHandler;
  976.   }
  977.   
  978.   initialized = 1;
  979.  
  980. }
  981.  
  982. /* This function will generate a breakpoint exception.  It is used at the
  983.    beginning of a program to sync up with a debugger and can be used
  984.    otherwise as a quick means to stop program execution and "break" into
  985.    the debugger. */
  986.    
  987. void breakpoint()
  988. {
  989.   if (initialized) BREAKPOINT();
  990. }
  991.  
  992.